import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { fetchCartPostSlice, IBall, IResponse } from './cart.actions';
import { fetchUserMeSlice } from './use.actions';

interface IBalls {
  user: IBall[];
  loading: boolean;
  errors: null;
  success: boolean;
}

const initialState = {
	user: {},
	loading: false,
	errors: null,
	success: false
};

export const cartSlice = createSlice({
	name: 'cart',
	initialState,
	reducers: {
		addBallToCart: (state, action) => {
			console.log('клик', action.payload);
			state.balls = [...state.balls, action.payload];
		},
		deleteBallOnCart: (state, action) => {
			state.balls = state.balls.filter(item => item.id !== action.payload);
		}
	},
	extraReducers: (builder) => {
		builder.addCase(fetchUserMeSlice.pending, (state) => {
			state.loading = true;
			state.errors = null;
		});
		builder.addCase(
			fetchUserMeSlice.fulfilled,
			(state, action) => {
				// if (!action.payload) {
				// 	state.balls.push(action.payload);
				// }
				state.loading = false;
			}
		);
		builder.addCase(fetchUserMeSlice.rejected, (state, action) => {
			// state.loading = true;
			state.errors = action.error.message;
		});
	}
});

export default cartSlice.reducer;
export const { addBallToCart, deleteBallOnCart } = cartSlice.actions;
